/*
 * Created with IDEA.
 * Description: A fully open-sourced high performance unibody close-loop driver for
 * Step-Motor, which was used in my DummyRobot project:
 * https://github.com/peng-zhihui/Dummy-Robot
 * Based on XDrive project: https://github.com/unlir/XDrive
 * @Author: Pengzhihui
 * @Date: ${DATE} ${TIME}
 *
 */

//
// Created by deng on 2022/12/25.
//
#include "tb67h450_stm32.h"
#include "bsp_tim.h"

void TB67H450::InitGpio() {
    GPIO_InitTypeDef GPIO_InitStruct = {0};

    /* Signal Ports Clock Enable */
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();

    /*Configure Signal pin Output Level */
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5,
                      GPIO_PIN_RESET);

    /*Configure Signal pins : PAPin PAPin PAPin PAPin */
    GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}

void TB67H450::InitPwm()
{
    MX_TIM2_Init();
}


void TB67H450::DacOutputVoltage(uint16_t _voltageA_3300mVIn12bits, uint16_t _voltageB_3300mVIn12bits) {
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, _voltageA_3300mVIn12bits >> 2);
    __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_3, _voltageB_3300mVIn12bits >> 2);
}


void TB67H450::SetInputA(bool _statusAp, bool _statusAm)
{
    _statusAp ? (GPIOA->BSRR = GPIO_PIN_5) : (GPIOA->BSRR = (GPIO_PIN_5<<16));
    _statusAm ? (GPIOA->BSRR = GPIO_PIN_4) : (GPIOA->BSRR = (GPIO_PIN_4<<16));
}


void TB67H450::SetInputB(bool _statusBp, bool _statusBm)
{
    _statusBp ? (GPIOA->BSRR = GPIO_PIN_3) : (GPIOA->BSRR = (GPIO_PIN_3<<16));
    _statusBm ? (GPIOA->BSRR = GPIO_PIN_2) : (GPIOA->BSRR = (GPIO_PIN_2<<16));
}
